package com.Brewing.springboot.controller.TpVideo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.Brewing.springboot.common.BrewingJSONResult;
import com.Brewing.springboot.common.FetchVideoCover;
import com.Brewing.springboot.common.MergeVideoMp3;
import com.Brewing.springboot.common.PagedResult;
import com.Brewing.springboot.common.enums.VideoStatusEnum;
import com.Brewing.springboot.controller.BasicController;
import com.Brewing.springboot.entity.TpBgm.TpBgm;
import com.Brewing.springboot.entity.TpComments.TpComments;
import com.Brewing.springboot.entity.TpVideos.TpVideos;
import com.Brewing.springboot.service.TpBgm.BgmService;
import com.Brewing.springboot.service.TpVideos.VideoService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @author 庄磊
 * @date 2018年12月21日 下午3:32:44
 * @version 1.0
 */
@RestController
@Api(value = "Video-Api", tags = { "Video-Api" })
@RequestMapping("/video")
public class VideoController extends BasicController {

	@Autowired
	private BgmService bgmService;

	@Autowired
	private VideoService videoService;

	@ApiOperation(value = "上传视频", notes = "上传视频的接口")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "form"),
			@ApiImplicitParam(name = "bgmId", value = "背景音乐id", required = false, dataType = "String", paramType = "form"),
			@ApiImplicitParam(name = "videoSeconds", value = "背景音乐播放长度", required = true, dataType = "String", paramType = "form"),
			@ApiImplicitParam(name = "videoWidth", value = "视频宽度", required = true, dataType = "String", paramType = "form"),
			@ApiImplicitParam(name = "videoHeight", value = "视频高度", required = true, dataType = "String", paramType = "form"),
			@ApiImplicitParam(name = "desc", value = "视频描述", required = false, dataType = "String", paramType = "form") })
	@PostMapping(value = "/upload", headers = "content-type=multipart/form-data")
	public BrewingJSONResult upload(String userId, String bgmId, double videoSeconds, int videoWidth, int videoHeight,
			String desc, @ApiParam(value = "短视频", required = true) MultipartFile file) throws Exception {
		if (StringUtils.isBlank(userId)) {
			return BrewingJSONResult.errorMsg("用户id不能为空...");
		}
		// 上传空间地址
		String fileSpace = FILE_SPACE;
		//本地
//		String fileSpace = "C:/Brewing-videos-dev";
		//服务器
//		String fileSpace = "/usr/local/brewing-video";
		String finalVideoPath="";
		// 保存到数据库的相对路径
		String uploadPathDB = "/" + userId + "/video";
		String coverPathDB = "/" + userId + "/video";
		FileOutputStream fileOutputStream = null;
		InputStream inputStream = null;
		try {
			if (file != null) {
				String fileName = file.getOriginalFilename();
				String arrayFilenameItem[] =  fileName.split("\\.");
				String fileNamePrefix = "";
				for (int i = 0 ; i < arrayFilenameItem.length-1 ; i ++) {
					fileNamePrefix += arrayFilenameItem[i];
				}
				if (StringUtils.isNotBlank(fileName)) {
					// 文件上传的最终保存路径
					finalVideoPath = fileSpace + uploadPathDB + "/" + fileName;
					// 设置数据库保存的路径
					uploadPathDB += ("/" + fileName);
					coverPathDB = coverPathDB + "/" + fileNamePrefix + ".jpg";
					File outFile = new File(finalVideoPath);
					if (outFile.getParentFile() != null || outFile.getParentFile().isDirectory()) {
						// 创建父文件夹
						outFile.getParentFile().mkdirs();
					}
					fileOutputStream = new FileOutputStream(outFile);
					inputStream = file.getInputStream();
					IOUtils.copy(inputStream, fileOutputStream);
				}
			} else {
				return BrewingJSONResult.errorMsg("上传出错...");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return BrewingJSONResult.errorMsg("上传出错...");
		} finally {
			if (fileOutputStream != null) {
				fileOutputStream.flush();
				fileOutputStream.close();
			}
		}
		// 判断bgmId是否为空，如果不为空，
		// 那就查询bgm的信息，并且合并视频，生产新的视频
		if (StringUtils.isNotBlank(bgmId)) {
			TpBgm bgm = bgmService.queryBgmById(bgmId);
			String mp3InputPath = FILE_SPACE + bgm.getPath();

			MergeVideoMp3 tool = new MergeVideoMp3(FFMPEG_EXE);
			String videoInputPath = finalVideoPath;

			String videoOutputName = UUID.randomUUID().toString() + ".mp4";
			uploadPathDB = "/" + userId + "/video" + "/" + videoOutputName;
			finalVideoPath = FILE_SPACE + uploadPathDB;
			tool.convertor(videoInputPath, mp3InputPath, videoSeconds, finalVideoPath);
		}
		// 对视频进行截图
		FetchVideoCover videoInfo = new FetchVideoCover(FFMPEG_EXE);
		videoInfo.getCover(finalVideoPath, FILE_SPACE + coverPathDB);

		// 保存视频信息到数据库
		TpVideos videos = new TpVideos();
		videos.setAudioId(bgmId);
		videos.setUserId(userId);
		videos.setVideoSeconds((float) videoSeconds);
		videos.setVideoHeight(videoHeight);
		videos.setVideoWidth(videoWidth);
		videos.setVideoDesc(desc);
		videos.setVideoPath(uploadPathDB);
		videos.setCoverPath(coverPathDB);
		videos.setStatus(VideoStatusEnum.SUCCESS.value);
		videos.setCreateTime(new Date());
		String videoId = videoService.saveVideo(videos);
		return BrewingJSONResult.ok(videoId);
	}

	@ApiOperation(value = "上传封面", notes = "上传封面的接口")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String", paramType = "form"),
			@ApiImplicitParam(name = "videoId", value = "视频主键id", required = true, dataType = "String", paramType = "form"), })
	@PostMapping(value = "/uploadCover", headers = "content-type=multipart/form-data")
	public BrewingJSONResult uploadCover(String videoId, String userId,
			@ApiParam(value = "封面", required = true) MultipartFile file) throws Exception {
		if (StringUtils.isBlank(videoId) || StringUtils.isBlank(userId)) {
			return BrewingJSONResult.errorMsg("视频主键id和用户不能为空...");
		}
		// 上传空间地址
		String fileSpace = FILE_SPACE;
		//本地
//		String fileSpace = "C:/Brewing-videos-dev";
		//服务器
		//String fileSpace = "/usr/local/Brewing-videos-dev";
		// 保存到数据库的相对路径
		String uploadPathDB = "/" + userId + "/video";
		FileOutputStream fileOutputStream = null;
		InputStream inputStream = null;
		String finalCoverPath = "";
		try {
			if (file != null) {
				String fileName = file.getOriginalFilename();
				if (StringUtils.isNotBlank(fileName)) {
					// 文件上传的最终保存路径
					finalCoverPath = fileSpace + uploadPathDB + "/" + fileName;
					// 设置数据库保存的路径
					uploadPathDB += ("/" + fileName);

					File outFile = new File(finalCoverPath);
					if (outFile.getParentFile() != null || outFile.getParentFile().isDirectory()) {
						// 创建父文件夹
						outFile.getParentFile().mkdirs();
					}
					fileOutputStream = new FileOutputStream(outFile);
					inputStream = file.getInputStream();
					IOUtils.copy(inputStream, fileOutputStream);
				}
			} else {
				return BrewingJSONResult.errorMsg("上传出错...");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return BrewingJSONResult.errorMsg("上传出错...");
		} finally {
			if (fileOutputStream != null) {
				fileOutputStream.flush();
				fileOutputStream.close();
			}
		}
		videoService.updateVideo(videoId, uploadPathDB);
		return BrewingJSONResult.ok();
	}
	/**
	 * 
	 * @Title:             showAll
	 * @Description:     分頁和搜索查詢視頻列表，isSaveRecord:1需要保存
	 * @return:         BrewingJSONResult   
	 */
	@ApiOperation(value = "查询视频", notes = "查询视频的接口")
	@PostMapping(value="/showAll")
	public BrewingJSONResult showAll(@RequestBody TpVideos videos,Integer isSaveRecord,@RequestParam(defaultValue = "1") Integer page) {
		PagedResult result= videoService.getAllVideos(videos,isSaveRecord,page, PAGE_SIZE);
		return BrewingJSONResult.ok(result);
	}
	/**
	 * @Title:             showMyFollow
	 */
	@PostMapping("/showMyFollow")
	public BrewingJSONResult showMyFollow(String userId,Integer page) {
		if(StringUtils.isBlank(userId)) {
			return BrewingJSONResult.ok();
		}
		if(page==null) {
			page=1;
		}
		int pageSize=6;
		PagedResult videosList = videoService.queryMyFollowVideos(userId,page,pageSize);
		return BrewingJSONResult.ok(videosList);
	}
	@PostMapping("/showMyLike")
	public BrewingJSONResult showMyLike(String userId,Integer page,Integer pageSize) {
		if(StringUtils.isBlank(userId)) {
			return BrewingJSONResult.ok();
		}
		if(page==null) {
			page = 1;
		}
		if(pageSize==null) {
			pageSize = 6;
		}
		PagedResult videosList = videoService.queryMyLikeVideos(userId,page,pageSize);
		return BrewingJSONResult.ok(videosList);
	}
	/**
	 * @Title:             hot
	 * @Description:     热搜
	 */
	@ApiOperation(value = "热搜视频", notes = "热搜视频的接口")
	@PostMapping(value="/hot")
	public BrewingJSONResult hot() {
		return BrewingJSONResult.ok(videoService.getHotwords());
	}
	@ApiOperation(value = "用户喜欢收藏", notes = "用户喜欢收藏的接口")
	@PostMapping(value="/userLike")
	public BrewingJSONResult userLike(String userId, String videoId, String videoCreaterId) 
			throws Exception {
		videoService.userLikeVideo(userId, videoId, videoCreaterId);
		return BrewingJSONResult.ok();
	}
	@ApiOperation(value = "用户不喜欢收藏", notes = "用户不喜欢收藏的接口")
	@PostMapping(value="/userUnLike")
	public BrewingJSONResult userUnLike(String userId, String videoId, String videoCreaterId) throws Exception {
		videoService.userUnLikeVideo(userId, videoId, videoCreaterId);
		return BrewingJSONResult.ok();
	}
	/**
	 * @Title:             saveComment
	 * @Description:     保存留言
	 */
	@ApiOperation(value = "保存留言", notes = "保存留言的接口")
	@PostMapping(value="/saveComment")
	public BrewingJSONResult saveComment(@RequestBody TpComments comment,String fatherCommentId, String toUserId) {
		comment.setFatherCommentId(fatherCommentId);
		comment.setToUserId(toUserId);
		comment.setLikeCount(0);
		videoService.saveComment(comment);
		return BrewingJSONResult.ok();
	}
	/**
	 * 点赞
	 * */
	@ApiOperation(value = "点赞", notes = "点赞的接口")
	@PostMapping(value="/likeComment")
	public BrewingJSONResult likeComment(String id) {
		videoService.likeComment(id);
		return BrewingJSONResult.ok();
	}
	/**
	 * @Title:             getVideoComments
	 * @Description:     查询单个视频
	 */
	@ApiOperation(value = "查询视频", notes = "查询指定视频的接口")
	@PostMapping(value="getVideoComments")
	public BrewingJSONResult getVideoComments(String videoId,@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "10") Integer pageSize) {
		if(StringUtils.isBlank(videoId)) {
			return BrewingJSONResult.ok();
		}
		//分页查询视频列表
		PagedResult list = videoService.getAllComments(videoId,page,pageSize);
		return BrewingJSONResult.ok(list);
	}
}
